package com.xinjian.jianba.filter;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xinjian.jianba.utils.AesUtil;
import com.xinjian.jianba.utils.QiNiuUtil;
import com.xinjian.jianba.utils.STSUtil;


public class ParameterFilter implements Filter{
	private static Logger LOGGER = LoggerFactory.getLogger(ParameterFilter.class);
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
		String url=requestWrapper.getRequestURI();
		if(!QiNiuUtil.backRequestUri.equals(url)&&!STSUtil.backRequestUri.equals(url)&&url.indexOf("/api/v3/jianba/tickets")==-1&&!"/api/v3/jianba/sts/videoInfo/ac/videoPath".equals(url)&&!"/api/v3/jianba/pay/notify/WEIXIN".equals(url)){
			byte[] signBody=requestWrapper.getBody();
			if(signBody!=null&&signBody.length!=0){
			String body = IOUtils.toString(signBody,request.getCharacterEncoding());
	        String decryptBody=AesUtil.decrypt(body);
//	        LOGGER.info("filter request body is {}",body);
	        requestWrapper.setBody(decryptBody.getBytes(request.getCharacterEncoding()));
	        }
		}
		
        chain.doFilter(requestWrapper, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
